﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

namespace Microsoft.Services.Clab.UI.Mvvmc
{
    public class KeyValueCollection : ObservableCollection<KeyValue>
    {
        public KeyValue this[string name]
        {
            get { return this.FirstOrDefault(p => p.Name == name); }
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
            if (e.NewItems != null)
            {
                foreach (KeyValue item in e.NewItems)
                {
                    item.PropertyChanged += Item_PropertyChanged;
                }
            }
            if (e.OldItems != null)
            {
                foreach (KeyValue item in e.OldItems)
                {
                    item.PropertyChanged -= Item_PropertyChanged;
                }
            }
        }

        private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
#if(!SILVERLIGHT)
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender));
#else
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, -1));
#endif
        }

        public bool CheckValue<T>(string name, Func<T, bool> valueFunc)
        {
            return this.Any(p => p.Name == name && valueFunc(p.GetValue<T>()));
        }

        public void Add(string name, object value)
        {
            this.Add(new KeyValue(name, value));
        }

        public bool Contains(string name)
        {
            return this.Any(p => p.Name == name);
        }
    }
}